<template>
  <view class="content">
    <view class="content-item">
      <view class="title">用户登录</view>
      <view class="form">
        <uv-form :model="form"
                 ref="uForm"
                 label-width="60px">
          <uv-form-item label="用户名" prop="name">
            <uv-input v-model="form.user_name" placeholder="请输入用户名"></uv-input>
          </uv-form-item>
          <uv-form-item label="密码" prop="pwd">
            <uv-input v-model="form.password" placeholder="请输入密码" password style="width: 100%;"></uv-input>
          </uv-form-item>
        </uv-form>
      </view>
      <view class="text" @click="jumpFn">无账号，去注册？</view>
      <view class="btn">
        <uv-button text="登录" type="primary"
                   @click="jumpAboutFn"
                   style="margin-top: 15px; width: 100%;"></uv-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";
import {Login} from "@/request/api"
const form = ref({
  user_name: "",
  password: ""
});
const uForm = ref(null)
const jumpFn = () => {
  uni.navigateTo({
    url: "/pages/register/register"
  });
};
const jumpAboutFn = () => {
  if (uForm.value) {
    uForm.value.validate().then(res => {
      uni.showLoading({ title: '登录中...' });

      Login(form.value)
          .then(response => {
            uni.hideLoading(); // 确保在这里调用
            if (response.code === 0) {
              uni.setStorageSync('user_name', form.value.user_name);
              uni.showToast({ title: '登录成功！' });
              uni.switchTab({ url: "/pages/about/about" });
            } else {
              uni.showToast({ icon: 'error', title: response.msg || '登录失败，请重试！' });
            }
          })
          .catch(err => {
            uni.hideLoading(); // 确保在这里调用
            console.error(err, '登录失败');
            uni.showToast({ icon: 'error', title: '网络错误，请重试！' });
          });
    }).catch(validationError => {
      uni.hideLoading(); // 确保在这里调用
      console.error(validationError, '表单验证失败');
      uni.showToast({ icon: 'error', title: '输入信息不完整' });
    });
  } else {
    console.error("表单未正确引用");
  }
};
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  width: 100%;
  height: 100vh;
  .content-item {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-sizing: border-box;
    padding: 0 30px;
    .title{
      margin-bottom: 20px;
      text-align: center;
      font-weight: bold;
      font-size: 30px;
    }
    .form{
      width: 100%;
    }
    .text{
      display: flex;
      width: 100%;
      justify-content: flex-end;
      margin: 15px 0;
    }
    .btn{
      width: 100%;
    }
  }
}


</style>